using ContentBanner.Models;
using Orchard;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Localization;
using Orchard.Settings;
namespace ContentBanner.Drivers {
    public class ContentBannerPartDriver : ContentPartDriver<ContentBannerPart> {
        private readonly ISiteService _siteService;
        private readonly IWorkContextAccessor _workContextAccessor;

        public Localizer T { get; set; }

        public ContentBannerPartDriver (ISiteService siteService, IWorkContextAccessor workContextAccessor) {
            _siteService = siteService;
            _workContextAccessor = workContextAccessor;
            T = NullLocalizer.Instance;
        }

        protected override string Prefix { get { return "ContentBanner"; } }


        protected override DriverResult Display(ContentBannerPart part, string displayType, dynamic shapeHelper)
        {
            var contentBannerSettings = _siteService.GetSiteSettings().As<ContentBannerSettingsPart>();
            
            var shape = shapeHelper.Parts_ContentBanner(
            Zone: contentBannerSettings.Zone,
            Position: contentBannerSettings.Position,
            ContentBanner: part);

            if (string.IsNullOrWhiteSpace(contentBannerSettings.Zone))
            {
                return ContentShape("Parts_ContentBanner", () => shape);
            }

            if (displayType == "Detail")
            {
                _workContextAccessor.GetContext()
                    .Layout.Zones[contentBannerSettings.Zone]
                    .Add(shape, contentBannerSettings.Position);
            }

            return new DriverResult();
        }


        // GET
        protected override DriverResult Editor(ContentBannerPart part, dynamic shapeHelper)
        {
            return ContentShape("Parts_ContentBanner_Edit", () =>
                shapeHelper.EditorTemplate(
                    TemplateName: "Parts.ContentBanner",
                    Model: part,
                    Prefix: Prefix));
        }


        // POST
        protected override DriverResult Editor(ContentBannerPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            updater.TryUpdateModel(part, Prefix, null, null);
            return Editor(part, shapeHelper);
        }
    }
}